const WXAPI = require('../../wxapi/main')
const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
const regeneratorRuntime = require('../../utils/runtime')

Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 300,
    goodsDetail: {},
    swiperCurrent: 0,
    selectSizePrice: 0,
    totalScoreToPay: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 1,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    currentPages: undefined,
    openShare: false
  },
 
  //事件处理函数
  swiperchange: function(e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  async onLoad(e) {
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene) // 处理扫码进商品详情页面的逻辑
      if (scene) {
        e.id = scene.split(',')[0];
      }
    }

    this.data.goodsId = e.id
    const that = this
    this.data.kjId = e.kjId
    if(e.share == 1){
      that.data.openShare = true;
      that.setData({
        openShare: true
      })
    }
   
    // 获取购物车数据
    wx.getStorage({
      key: 'shopCarInfo',
      success: function(res) {
        that.setData({
          shopCarInfo: res.data,
          shopNum: res.data.shopNum,
          curuid: wx.getStorageSync('uid')
        });
      }
    })
    this.reputation(e.id)
  },
  onShow (){
    let that = this;
    that.setData({
      vipLevel: app.globalData.vipLevel,
      curuid: wx.getStorageSync('uid')
    })
    this.getGoodsDetailAndKanjieInfo(this.data.goodsId)
  },
  async getGoodsDetailAndKanjieInfo(goodsId) {
    const that = this;
    const goodsDetailRes = await WXAPI.goodsDetail(goodsId)
    //获取我发起的砍价活动
    const goodsKanjiaSetRes = await WXAPI.kanjiaSet(goodsId)
    if (goodsDetailRes.type == 'success') {
      //获取商品详情
      that.data.goodsDetail = goodsDetailRes.resultData.row;
      if (that.data.goodsDetail.spurl) {
        that.data.goodsDetail.pics.unshift({ url: that.data.goodsDetail.spurl, isvideo:true});
      }
      that.data.goodsDetail.guigepic = that.data.goodsDetail.picurl;
      that.data.goodsDetail.kucun = that.data.goodsDetail.bbnum;

      let _data = {
        goodsDetail: goodsDetailRes.resultData.row,
        buyNumMax: 100000,
        buyNumber: 1,
      }

      // 如果kjId为空，进行赋值
      if (goodsKanjiaSetRes.type == 'success') {
        _data.curGoodsKanjia = goodsKanjiaSetRes.resultData.row
        // 这个人本身也有活动
        if (_data.curGoodsKanjia) {
          // 获取当前砍价进度
          if (!that.data.kjId) {
            that.data.kjId = _data.curGoodsKanjia.id
          }
        }
        // 要参与的砍价情况
        if (that.data.kjId){
          let curKanjiaprogress = await WXAPI.kanjiaDetail(that.data.kjId)
          let myHelpDetail = await WXAPI.kanjiaHelpDetail(that.data.kjId)
          if (curKanjiaprogress.type == 'success') {
            _data.curKanjiaprogress = curKanjiaprogress.resultData.row
          }
          if (myHelpDetail.type == 'success') {
            _data.myHelpDetail = myHelpDetail.resultData.row
          }
        }    
      }  

      that.setData(_data);
      WxParse.wxParse('article', 'html', goodsDetailRes.resultData.row.detail.content, that, 5);
    }
  },
  goShopCar: function() {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  },
  goAddress() {
    const that = this;
    if (that.data.goodsDetail.zuobiao){
      var zuobiao = that.data.goodsDetail.zuobiao.split(",");
      wx.getLocation({//获取当前经纬度
        type: 'wgs84', //返回可以用于wx.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息  
        success: function (res) {
          wx.openLocation({//​使用微信内置地图查看位置。
            latitude: Number(zuobiao[0]),//要去的纬度-地址
            longitude: Number(zuobiao[1]),//要去的经度-地址
            name: that.data.goodsDetail.dizhi,
            address: that.data.goodsDetail.dizhi
          })
        }
      });
    }
  },
  govip: function () {
    wx.navigateTo({
      url: "/pages/fx/apply-status"
    });
  }, 
  toAddShopCar: function() {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  tobuy: function() {
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  buyNumberInput: function(e) {
    this.setData({
      buyNumber: e.detail.value
    })
  },
  numJiaTap: function() {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  


  /**
     * 选择商品规格
     * @param {Object} e
     */
  choosecolorTap: function (e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.goodsDetail.yansePics;
    for (var i = 0; i < childs.length; i++) {
      childs[i].active = false;
    }
    // 设置当前选中状态
    childs[e.currentTarget.dataset.propertyindex].active = true;
    that.data.goodsDetail.guige = childs[e.currentTarget.dataset.propertyindex];
    this.setData({
      goodsDetail: that.data.goodsDetail,
    })
    this.bindGuiGeTap();
  },
  /**
   * 立即购买
   */
  buyNow: function(e) {
    let that = this;
    //组建立即购买信息
    var buyNowInfo = this.buliduBuyNowInfo();
    if (!buyNowInfo.yanse) {
      wx.showModal({
        title: '提示',
        content: '请选择商品！',
        showCancel: false
      })
      return;
    }
    // 写入本地存储
    wx.setStorage({
      key: "buyNowInfo",
      data: buyNowInfo
    })
    this.closePopupTap();
    wx.navigateTo({
      url: "/pages/to-pay-order/index?orderType=buyNow"
    })

  },
  /**
   * 组建立即购买信息
   */
  buliduBuyNowInfo: function() {
    var shopCarMap = {};
    shopCarMap.bbid = this.data.goodsDetail.id;
    var colors = this.data.goodsDetail.yansePics;
    for (var i = 0; i < colors.length; i++) {
      if (colors[i].active){
        shopCarMap.yanse = colors[i].yanse
      }
    }
    shopCarMap.bbnum = 1;
    return shopCarMap;
  },
  onShareAppMessage: function() {
    let _data = {
      title: this.data.goodsDetail.title,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.id + '&inviter_id=' + wx.getStorageSync('uid'),
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
    if (this.data.kjId) {
      _data.title = this.data.curKanjiaprogress.user.nickname + '邀请您帮TA砍价'
      _data.path += '&kjId=' + this.data.kjId
    }
    return _data
  },
  reputation: function(goodsId) {
    var that = this;
    // WXAPI.goodsReputation({
    //   goodsId: goodsId
    // }).then(function(res) {
    //   if (res.code == 0) {
    //     that.setData({
    //       reputation: res.data
    //     });
    //   }
    // })
  },
  joinKanjia: function() { // 报名参加砍价活动
    const _this = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    WXAPI.kanjiaJoin(_this.data.goodsDetail.id).then(function(res) {
      wx.hideLoading();
      if (res.type == 'success') {
        _this.data.kjId = res.resultData.row.id
        _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.id)
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    })
  },
  joinPingtuan: function(e) {
    let pingtuanopenid = e.currentTarget.dataset.pingtuanopenid
    wx.navigateTo({
      url: "/pages/to-pay-order/index?orderType=buyNow&pingtuanOpenId=" + pingtuanopenid
    })
  },
  helpKanjia() {
    const _this = this;
    WXAPI.kanjiaHelp(_this.data.kjId).then(function (res) {
      if (res.type != 'success') {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
        return;
      }
      _this.setData({
        myHelpDetail: res.resultData.row
      });
      wx.showModal({
        title: '成功',
        content: '成功帮TA砍掉 ' + res.resultData.row.curPrice + ' 元',
        showCancel: false
      })
      _this.getGoodsDetailAndKanjieInfo(_this.data.goodsDetail.id)
    })
  },
  openShareDiv () {
    this.setData({
      openShare: true
    })
  },
  closeShareDiv() {
    this.setData({
      openShare: false
    })
  },
  toPoster: function (e) { // 千万生成海报界面
    var goodsDetailtemp = this.data.goodsDetail;
    var url = goodsDetailtemp.id + ',' + wx.getStorageSync('uid');
    var datatemp = { url: url, name: goodsDetailtemp.title, pic: encodeURIComponent(goodsDetailtemp.downloadUrl), path:"pages/goods-details/index"};
    wx.navigateTo({
      url: "/pages/goods-details/poster?datastr=" + JSON.stringify(datatemp) 
    })
  }
})